﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Diagnostics;

namespace IboxWebSite.Library.Authenticate
{
    public class AuthenticateUtility
    {

        public const string MEMBER_PREFIX = "Ibox_User";

        public static string GetUsername()
        {
            return HttpContext.Current.User.Identity.Name.Replace(MEMBER_PREFIX, string.Empty);
        }

        public static bool IsAuthenticated()
        {
            HttpContext context = HttpContext.Current;
            return
                context.User.Identity.IsAuthenticated && (context.User.Identity.Name.IndexOf(MEMBER_PREFIX) != -1);
        }

        public static void LoginUser(string _username, bool _rememberAccount)
        {
            LogoutUser();
            FormsAuthentication.Initialize();
            DateTime dt = DateTime.Now.AddMinutes(30);
            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, MEMBER_PREFIX + _username, DateTime.Now, dt, _rememberAccount, "", FormsAuthentication.FormsCookiePath);
            Trace.Write(FormsAuthentication.FormsCookiePath + FormsAuthentication.FormsCookieName);
            HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket));
            HttpContext.Current.Response.SetCookie(cookie);
        }

        public static void LogoutUser()
        {
            HttpContext.Current.Items.Remove("AGENT_INFO");
            HttpContext.Current.Items.Remove("CUSTOMER_INFO");
            HttpContext.Current.Session.Abandon();
            FormsAuthentication.SignOut();
        }
    }
}
